<template>
  <div class="dialogue">
    <el-form class="formBox" :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="false"
             label-width="68px">
      <el-form-item label="医院" prop="hospital" clearable>
        <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="200px"
                    ref="department"></department>
      </el-form-item>
    </el-form>
    <div class="content" ref="chatRoom">
      <div class="msg-list" :class="popupLayerClass">
        <div class="message">
          <div class="row" v-for="(item,index) in list" :key="index" :id="'chat_item_'+item.id">
            <!-- 用户消息 -->
            <!-- 自己发出的消息 -->
            <div class="my" v-if="item.from_id==user.wssUuid">
              <div class="left">
                <!-- 文字和图片消息 -->
                <div class="username">
                  <div class="time">{{ item.create_time|formatTime }}</div>
                </div>
                <div class="fail" v-if="item.sendStatus==='fail'">!</div>

                <div class="bubble">
                  <el-image v-if="item.type=='image'" :preview-src-list="srcList"
                            fit="contain" style="width: 130px; height: 100px" :src="changeUrl(item.data)">
                  </el-image>
                  <div v-else>
                    {{ item.data }}
                  </div>
                </div>
              </div>
              <!-- 右-自己头像 -->
              <div class="right" >
                <el-image style="width: 50px; height: 50px;border-radius:50%;border: 1px solid #C4C4C5" :src='myAvatar'>
                  <div slot="error" class="flex align-center justify-center " >
                    <i class="el-icon-user" style="font-size: 32px;line-height: 50px"></i>
                  </div>
                </el-image>


              </div>
            </div>
            <!-- 别人发出的消息 -->
            <div class="other" v-else>
              <!-- 左-别人头像 -->
              <div class="left" @click="goInfo(item)">
                <el-image style="width: 50px; height: 50px;border-radius:50%;border: 1px solid #C4C4C5" :src='otherAvatar'>
                  <div slot="error" class="flex align-center justify-center " >
                    <i class="el-icon-user" style="font-size: 32px;line-height: 50px"></i>
                  </div>
                </el-image>
                <img v-if="item.extend.patientId"
                  class="leftImage"
                  :src="require('@/assets/images/gesture.png')"
                  alt=""
                />
              </div>
              <!-- 左-用户名称-时间-消息 -->
              <div class="right">
                <div class="username">
                  <div class="time">{{ item.create_time|formatTime }}</div>
                  <div class="timeId" v-if="item.extend.patientId">顾客ID:{{item.extend.patientId}}</div>
                </div>
                <!-- 文字和图片消息 -->
                <div class="bubble">
                  <el-image :preview-src-list="srcList" v-if="item.type=='image'"
                            fit="contain" style="width: 130px; height: 100px" :src="changeUrl(item.data) ">
                  </el-image>
                  <div v-else>
                    {{ item.data }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="footer">
      <div class="toolBox">
        <div class="phrase">
          <el-dropdown  @command="handleCommand" trigger="click">
            <el-button size="small" >
              常用语<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item v-for="(item,index) in phrasesList" :key="index" :command="item.phrases">{{ item.phrases }}</el-dropdown-item>
            </el-dropdown-menu>

          </el-dropdown>
        </div>
        <div class="phrase">
          <el-button size="small" icon="el-icon-edit" @click="handleOpen">常</el-button>
        </div>
        <div>
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="uploadUrl"
            :headers="headerObj"
            :before-upload="beforeImageUpload"
            :on-success="handleImageSuccess"
            :file-list="fileList"
            :show-file-list="true">
            <el-button  icon="el-icon-picture-outline" size="small" >照片上传</el-button>
          </el-upload>
        </div>

      </div>
      <div>
        <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="textMsg">
        </el-input>
      </div>
      <div class="sendBox">
        <el-button size="small" type="primary" plain @click="sendText">发送</el-button>
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog title="常用语" v-dialogDrag :visible.sync="phrasesOpen" width="600px" append-to-body :before-close="handleCancel"
               :close-on-click-modal="false">
      <div class="mb8">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </div>
      <el-table  :data="phrasesList" border>
        <el-table-column label="常用语" align="center" prop="phrases" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" fixed="right" width="160"
                         class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       :disabled="scope.row.userId===0">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog title="新增常用语" :visible.sync="open" width="600px" append-to-body :before-close="cancel"
               :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left" class="formBox1">
        <el-row>
          <el-col :span="24">
            <el-form-item label="使用科室" prop="deptId" v-if="open">
              <department :isAdd="true" @changedepatData="changedepatData" :HospitalId="form.hospitalId"
                          :deptIds="form.deptId" :isdisabled="false"></department>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="常用语" prop="phrases">
              <el-input type="textarea" v-model="form.phrases"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailDialogVisible"
      :width="device !== 'mobile' ? '85%' : '100%'"
      center
      append-to-body
      :close-on-click-modal="false"
      class="nopaddingDailog"
      :class="device !== 'mobile' ? '' : 'active'"
      v-dialogDrag
    >
      <CustomerDetails
        v-if="detailDialogVisible"
        :basicInfo="basicInfo"
      ></CustomerDetails>
    </el-dialog>





  </div>

</template>

<script>

import freeBase from "@/utils/mixin/free-base.js"
import $C from '@/utils/socketConfig'
import {
  getToken,
} from '@/utils/auth'
import {
  mapState,
  mapMutations, mapGetters
} from 'vuex'
import department from "@/views/components/department/index.vue";
import CustomerDetails from "@/views/components/customerDetail/customerDetail";
import {
  addPhrases,
  deleteUserPhrases,
  listAllPhrases,

} from "@/api/system/phrase";
import {consentList} from "@/api/treatmentWorkstation/treatmentManagement";


export default {
  mixins: [freeBase],
  components:{
    department,
    CustomerDetails
  },
  data() {
    return {
      hospital: {}, //选择的医院
      userId: '',
      wssUuid: '',
      key: '',
      list: [], //消息列表
      messageIndex: 0, // 删掉
      user: {},
      textMsg: '', //发送聊天文字
      isHistoryLoading: false,
      scrollAnimation: false,
      scrollTop: 0,
      scrollToView: '',
      popupLayerClass: '', // 抽屉参数
      hideMore: true,  // more参数
      show: false,
      chatObj: '',
      srcList: [],
      uploadUrl:$C.socketXhrUrl+'/upload',
      headerObj: {
        Token: getToken()
      },
      myAvatar:'',
      otherAvatar:'',
      fileList:[],
      phrasesList:[],
      // 是否显示弹出层
      open: false,
      phrasesOpen: false,
      // 查询参数
      queryParams: {
        hospitalId: undefined,
        deptId: undefined,
        isPatient:0,
        userId:'',
      },
      form :{
        deptId: undefined,
        hospitalId: undefined,
        isPatient: 0,
        userId:'',
        phrases:'',
      },
      rules: {
        isPatient: [
          {
            required: true,
            message: "用户类别必选",
            trigger: "blur",
          },
        ],
        phrases: [
          {
            required: true,
            message: "常用语必填",
            trigger: "blur",
          },
        ],
        deptId: [
          {
            required: true,
            message: "科室必选",
            trigger: "blur",
          },
        ],
      },
      detailTitle: "",
      detailDialogVisible: false,
      basicInfo: {},



    }
  },
  computed: {
    ...mapState({
      chat: state => state.user.chat,
      chatObjItem: state => state.user.chatObj,
      chatDetail: state => state.user.chatDetail,
    }),
    ...mapGetters([ "device"]),
  },
  watch: {
    chatDetail(newVal, oldVal) {
      // console.log('newVal+++',newVal)
      // console.log('oldVal---',oldVal)
      // let newObj = newVal.at(-1)
      let newObj = newVal[newVal.length-1]
      if (this.chatObj.wssUuid == newObj.from_id) {
        this.list = newVal
        this.srcList = []
        if (this.list.length > 0) {
          this.list.forEach(item => {
            if (item.type == 'image') {
              this.srcList.push(this.changeUrl(item.data) )
            }

          })
        }

        this.pageToBottom()
      }

    },

    chatObjItem(newVal, oldVal) {
      // console.log('newVal+++',newVal)
      // console.log('oldVal---',oldVal)
      this.chatObj = newVal
      this.otherAvatar=process.env.VUE_APP_BASE_API +this.chatObj.avatar
      if (this.chatObj.id) {
        this.chatObj.wssUuid = this.chatObj.id
      }
      this.chat.createChatObject({
        id: this.chatObj.wssUuid,
        chat_type: 'user',
        avatar: this.chatObj.avatar,
      })
      this.key =
        `hospitalId_${this.hospital.deptId}_chatDetail_${this.user.wssUuid}_user_${this.chatObj.wssUuid}`
      this.list = this.chat.getChatDetail(this.key)
      this.srcList = []
      if (this.list.length > 0) {
        this.list.forEach(item => {
          if (item.type == 'image') {
            this.srcList.push(this.changeUrl(item.data))
          }
        })
      }
      this.pageToBottom()

    }

  },

  mounted() {
    this.user = JSON.parse(localStorage.getItem('user'))
    this.hospital = JSON.parse(localStorage.getItem('hospital'))
    this.myAvatar=process.env.VUE_APP_BASE_API +this.user.avatar

    this.chatObj = this.chatObjItem
    this.otherAvatar=process.env.VUE_APP_BASE_API + this.chatObj.avatar

    if (this.chatObj.id) {
      this.chatObj.wssUuid = this.chatObj.id
    }
    this.chat.createChatObject({
      id: this.chatObj.wssUuid,
      chat_type: 'user',
      avatar: this.chatObj.avatar,
    })
    this.key =
      `hospitalId_${this.hospital.deptId}_chatDetail_${this.user.wssUuid}_user_${this.chatObj.wssUuid}`
    this.list = this.chat.getChatDetail(this.key)
    this.srcList = []
    if (this.list.length > 0) {
      this.list.forEach(item => {
        if (item.type == 'image') {
          this.srcList.push(this.changeUrl(item.data))
        }
      })

    }
    this.pageToBottom()
    this.getPhraseList()



  },
  methods: {
    goInfo(item){
      if(item.extend.isPatient == 1){
        if(item.extend.patientId){
          this.detailTitle = "顾客详情";
          this.basicInfo = item.extend;
          this.detailDialogVisible = true;
        }else{
          this.$message({
            message: '暂无登记信息~',
            type: 'warning'
          });
        }
      }else if(item.extend.isPatient == 2){
        if(item.extend.patientId){
          this.detailTitle = "顾客详情";
          this.basicInfo = item.extend;
          this.detailDialogVisible = true;
        }else{
          this.$message({
            message: '此为医生无法查看信息~',
            type: 'warning'
          });
        }

      }else{
        this.$message({
          message: '此为医生无法查看信息~',
          type: 'warning'
        });
      }

    },
    handleCommand(command) {
      this.textMsg=command
    },
    handleImageSuccess(res, file,fileList){
      console.log('handleImageSuccess---fileList',fileList)
       if(fileList.every(item => item.status === 'success')){
         this.$refs.upload.clearFiles();
       }
      console.log('handleImageSuccess---',res, file)
      const uploadResult=res.data
      const extend = {
        userId: this.user.userId,
        isPatient: this.user.isPatient,
        patientId: this.hospital.patientId,
        hospitalId:this.hospital.deptId,
      }
      this.send('image', uploadResult, {}, extend)

    },
    refreshData(data) {
      this.queryParams.hospitalId = data.hospitalId
      this.queryParams.deptId = data.deptId
      this.queryParams.userId = this.user.userId
      this.getPhraseList()
    },
    changedepatData(data) {
      if (data && data.length > 0) {
        this.form.deptId = data[0].deptId
        this.form.hospitalId = data[0].parentId
      } else {
        this.form.deptId = undefined
        this.form.hospitalId = undefined
      }
    },

    getPhraseList() {
      listAllPhrases(
        this.queryParams
      ).then((response) => {
        if(response.code==200){
          this.phrasesList = response.data;
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.form.userId=this.user.userId
      console.log(this.form.detectionIds)
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addPhrases(this.form).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getPhraseList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm(
          '是否确认删除该数据项？'
        )
        .then(function () {
          return deleteUserPhrases(id);
        })
        .then(() => {
          this.getPhraseList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    handleAdd(){
      this.reset();
      this.open = true;
    },
    handleOpen(){
      this.phrasesOpen = true;
    },
    handleCancel(){
      this.phrasesOpen = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        hospitalId: undefined,
        isPatient: 0,
        phrases:'',
      };
      this.resetForm("form");
    },
    beforeImageUpload(file){
      console.log('beforeImageUpload',file)
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError(
          "文件格式错误，请上传图片类型,如：JPG，PNG后缀的图片。"
        );
      }
    },
    changeUrl(url){
      return url.replace('http','https').replace('9000','9003')
    },
    sendText() {
      if (!this.textMsg) {
        return;
      }
      const extend = {
        userId: this.user.userId,
        isPatient: this.user.isPatient,
        patientId: this.hospital.patientId,
        hospitalId: this.hospital.deptId,
      }
      // this.messageIndex +=1
      // this.send('text', `发送消息_${this.messageIndex}`,{}, extend)
      this.send('text', this.textMsg, {}, extend)
    },
    // 发送
    send(type, data = '', options = {}, extend = {}) {
      // 组织数据格式
      switch (type) {
        case 'text':
          data = data || this.text
          break;
      }
      let message = this.chat.formatSendData({
        type,
        data,
        options,
        extend
      })
      // 渲染到页面
      let index = this.list.length
      this.list.push(message)
      // 监听上传进度
      let onProgress = false
      if (message.type !== 'text' && message.type !== 'emoticon' && message.type !== 'card' && !message.data
        .startsWith('http')) {
        onProgress = (progress) => {
          console.log('上传进度：', progress);
        }
      }
      // 发送到服务端
      this.chat.send(message, onProgress).then(res => {
        console.log(' 发送到服务端', res);
        // 发送成功
        this.list[index].id = res.id
        this.list[index].sendStatus = 'success'
        // 发送文字成功，清空输入框
        if (type === 'text') {
          this.textMsg = ''
        }
        if (res.type == 'image') {
          this.srcList.push(this.changeUrl(res.data) )
        }
        this.pageToBottom()

      }).catch(err => {
        // 发送失败
        this.list[index].sendStatus = 'fail'
        this.pageToBottom()
        console.log(err);

      })

    },
    pageToBottom() {
      // this.$nextTick 将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它，然后等待DOM更新
      this.$nextTick(() => {
        // dom 元素更新后执行滚动条到底部 否则不生效
        let scrollElem = this.$refs.chatRoom;
        // console.log('scrollHeight: ', scrollElem.scrollHeight);
        // scrollElem.scrollTop = scrollElem.scrollHeight
        scrollElem.scrollTo({
          top: scrollElem.scrollHeight,
          behavior: 'smooth'
        });
      });
    },

  }

}
</script>

<style scoped lang="scss">
.dialogue {
  position: relative;
  height: 100%;

  .content {
    width: 100%;
    height: calc(100% - 150px);
    overflow: hidden;
    overflow-y: scroll;

    .msg-list {
      width: 100%;
      padding: 0 15px;

      &.showLayer {
        // transform: translate3d(0, -42vw, 0);
        bottom: 420px;
      }

      .message {
        .row {
          &:first-child {
            margin-top: 20px;
          }

          padding: 10px 0;

          .my .left,
          .other .right {
            width: 100%;
            display: flex;

            .bubble {
              border-radius: 10px;
              padding: 10px;
              display: flex;
              align-items: center;
              font-size: 18px;
              word-break: break-word;

              &.img {
                background-color: transparent;
                padding: 0;
                overflow: hidden;

                image {
                  max-width: 350px;
                  max-height: 350px;
                }
              }

              &.red-envelope {
                background-color: transparent;
                padding: 0;
                overflow: hidden;
                position: relative;
                justify-content: center;
                align-items: flex-start;

                image {
                  width: 250px;
                  height: 313px;
                }

                .tis {
                  position: absolute;
                  top: 6%;
                  font-size: 26px;
                  color: #9c1712;
                }

                .blessing {
                  position: absolute;
                  bottom: 14%;
                  color: #e9b874;
                  width: 80%;
                  text-align: center;
                  overflow: hidden;
                  // 最多两行
                  display: -webkit-box;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 2;
                }
              }

              &.voice {
                .icon {
                  font-size: 40px;
                }

                display: flex;
                align-items: center;
              }

              .icon:after {
                content: " ";
                width: 53px;
                height: 53px;
                border-radius: 100%;
                position: absolute;
                box-sizing: border-box;
              }

              .length {
                font-size: 28px;
              }
            }
          }
        }

        .my .right,
        .other .left {
          flex-shrink: 0;
          position: relative;
          .leftImage{
            position: absolute;
            right: 0px;
            top:50px ;
          }
        }

        .my {
          width: 100%;
          display: flex;
          justify-content: flex-end;

          .left {
            flex-wrap: wrap;
            min-height: 80px;
            align-items: center;
            justify-content: flex-end;

            .username {
              width: 100%;
              height: 45px;
              font-size: 16px;
              color: #999;
              display: flex;
              justify-content: flex-end;

              .time {
                margin-right: 4px;

              }
            }

            .fail {
              width: 25px;
              height: 25px;
              border-radius: 50%;
              background-color: red;
              text-align: center;
              margin-right: 5px;
              font-size: 20px;
              line-height: 25px;
              color: #ffffff;
            }

            .bubble {
              // background-color: #95EC69;
              // color: #000;
              background-color: #95EC69;
              color: #232323;
              max-width: 75%;


            }
          }

          .right {
            margin-left: 15px;
            margin-right: 25px;
          }
        }

        .other {
          width: 100%;
          display: flex;

          .left {
            margin-right: 15px;
            margin-left: 25px;
          }

          .right {
            flex-wrap: wrap;

            .username {
              width: 100%;
              height: 45px;
              font-size: 16px;
              color: #999;
              display: flex;

              .name {
                margin-right: 50px;
              }
              .timeId{
                margin-left: 5px;
                color: #1890FF;

              }
            }

            .bubble {
              background-color: #fff;
              color: #333;
              //background-color: #F6F6F6;
              //color: #4D4D4D;
              max-width: 75%;


            }
          }
        }
      }
    }
  }

  .footer {
    width: 100%;
    height: 150px;
    padding: 0 10px;
    border-top: 1px solid #C4C4C5;
    position: absolute;
    bottom: 0px;

    .toolBox {
      padding: 5px 0;
      display: flex;
      .phrase{
        margin-right: 5px;
      }
      .upload-demo{
        display: flex;
      }

    }

    .sendBox {
      //text-align: right;
      position: absolute;
      right: 10px;
      bottom: 0px;

    }


  }


}

</style>
